package com.dylovedz.javafxphone.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dylovedz.javafxphone.controller.vo.PhoneExcelVO;
import com.dylovedz.javafxphone.util.ExcelUtil;
import com.dylovedz.javafxphone.util.PhoneUtil;
import javafx.concurrent.Task;

import java.io.BufferedInputStream;
import java.io.File;
import java.util.List;
import java.util.Map;

public class PhoneExportTask extends Task<Number> {

    private String outDir;

    private String inFile;

    public PhoneExportTask(String inFile, String outDir) {
        this.inFile = inFile;
        this.outDir = outDir;
    }

    @Override
    protected Number call() throws Exception {
        BufferedInputStream stream = FileUtil.getInputStream(inFile);
        List<PhoneExcelVO> readList = ExcelUtil.read(stream, PhoneExcelVO.class);
        if (ObjectUtil.isEmpty(readList)) {
            this.updateMessage("excel没有数据或头部格式不正确，请确保头部存在“手机号”列");
            return 0;
        }
        double max = readList.size() + (readList.size() * 0.1);
        double done = 0;
        for (PhoneExcelVO phoneExcelVO : readList) {
            if (!PhoneUtil.isValid(phoneExcelVO.getPhone())) {
                phoneExcelVO.setCarrier("格式错误");
                phoneExcelVO.setGeo("格式错误");
            } else {
                String geo = PhoneUtil.getGeo(phoneExcelVO.getPhone());
                if (ObjectUtil.equals(geo, "中国") || ObjectUtil.isEmpty(geo)) {
                    Map<String, String> phoneGeo = PhoneUtil.getPhoneByHttp(phoneExcelVO.getPhone());
                    phoneExcelVO.setGeo(phoneGeo.get("geo"));
                    phoneExcelVO.setCarrier(phoneGeo.get("carrier"));
                } else {
                    phoneExcelVO.setGeo(geo);
                    phoneExcelVO.setCarrier(PhoneUtil.getCarrier(phoneExcelVO.getPhone()));
                }
            }
            done++;
            this.updateProgress(done, max);
        }
        String date = DateUtil.format(DateUtil.date(), "MMddHHmmss");
        File file = FileUtil.file(FileUtil.file(outDir), "phone" + date + ".xlsx");
        ExcelUtil.write(file, "归属地查询", PhoneExcelVO.class, readList);
        this.updateMessage("导出成功");
        this.updateProgress(max, max);
        return 1;
    }
}
